<?php namespace Admin\Model;
class Goods extends \Hdphp\Model\Model{
	//商品表
	protected $table ='shop_goods';

	 //自动验证
	protected $validate = array( 
		array('goods_name','required','商品名称不能为空',3,3),
		); 

    //自动完成
	protected $auto=array(
		array('create_at','time','function',3,1),
		array('admin_id','getAdminId','method',3,1),
		array('index_pic','getIndexPic','method',3,3),
		array('list_pic','getListPic','method',3,3),
		array('thumb_pic','getThumbPic','method',3,3),
		);

    //自动完成，获取商品的管理员id
	protected function getAdminId()
	{
		return $_SESSION['admin_id'];
	}
	//自动完成，获取商品的首页大图
	protected function getIndexPic()
	{
		if($file=Upload::make('index_pic'))
		{
			return $file[0]['path'];
		}
		return Q('post.index_pic','');
	}
    //自动完成，获取商品的列表页图片
	protected function getListPic()
	{
		if($file = Upload::make('list_pic'))
		{
			return $file[0]['path'];
		}
		return Q('post.list_pic','');
	}

    //自动完成，获取商品的缩略图片
	protected function getThumbPic()
	{
		if($file = Upload::make('thumb_pic'))
		{
			return $file[0]['path'];
		}
		return Q('post.thumb_pic','');
	}

	//获取所有商品
	public function getAll($cat_id=''){
		if($cat_id)
		{
			//读取指定栏目的商品
			$page = Page::make($this->where("cat_id=$cat_id and is_delete=0")->count());
			$data = Db::table('shop_goods g')->where("cat_id=$cat_id and is_delete=0")
			->limit(Page::limit())
			->join('shop_cat c','g.cat_id','=','c.cat_id')->get();
		}
		else
		{
			//读取所有商品
			$page = Page::make($this->count());
			$data = Db::table('shop_goods g')->where("is_delete=0")
			->limit(Page::limit())->join('shop_cat c','g.cat_id','=','c.cat_id')->get();
		}
		
		return array('data'=>$data,'page'=>$page);
	}

	//添加商品
	public function store()
	{
		if($this->create())
		{
			if($goods_id = $this->add())
			{
				//图集处理
				$pics = new \Admin\Model\Pics;
				$pics->store($goods_id);
				//商品属性处理
				$goodsAttr = new \Admin\Model\GoodsAttr;
				$goodsAttr->addGoodsAttr($goods_id);
			}
			return true;
		}
	}

	//修改商品
	public function edit()
	{
		if($this->create())
		{
			if($this->save())
			{
				//图集处理
				$pics = new \Admin\Model\Pics;
				$pics->store($_POST['goods_id']);
				//商品属性处理
				$goodsAttr = new \Admin\Model\GoodsAttr;
				$goodsAttr->addGoodsAttr($_POST['goods_id']);
			}
			return true;
		}
	}

	//读取商品数据
	public function one($goods_id)
	{
		return $this->find($goods_id);
	}

}
























